package com.runtime.hongyunmanage.controller;


import com.alibaba.druid.util.StringUtils;
import com.runtime.hongyunmanage.domain.Manager;
import com.runtime.hongyunmanage.domain.vo.ManagerVo;
import com.runtime.hongyunmanage.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/manager")
public class MangerController {

    @Autowired
    private ManagerService managerService;
    @PostMapping("/login")
    public Result login(@RequestBody ManagerVo managerVo, HttpServletRequest req) {
        String trueCode = (String) req.getSession().getAttribute("code"); // 正确验证码
        String inputCode = managerVo.getCode();
        String managerAcc = managerVo.getManagerAcc();
        String managerPwd = managerVo.getManagerPwd();
//
        if (!isAccountExists(managerAcc)) {
            return new Result(Code.GET_ERR, -1, "登录失败,账号不存在");
        }

        if (!isPasswordCorrect(managerAcc,managerPwd)) {
            return new Result(Code.GET_ERR, -2, "登录失败,密码不正确");
        }

        if (!inputCode.equals(trueCode)) {
            return new Result(Code.GET_ERR, 0, "登录失败,验证码不正确");
        }

        Object userPower = managerService.selectManagerPwd(managerAcc, managerPwd);
        req.getSession().setAttribute("manage", userPower);
        return new Result(Code.GET_OK, 1, "登录成功");
    }
    private boolean isAccountExists(String managerAcc) {
        List<Manager> tbluserAcc = managerService.selectManagerAcc(managerAcc);
        return tbluserAcc.size() > 0;
    }

    private boolean isPasswordCorrect(String managerAcc,String managerPwd) {
        List<Manager> tbluserPwd = managerService.selectManagerPwd(managerAcc,managerPwd);
        return tbluserPwd.size() > 0;
    }

    @PostMapping
    public Result insert(@RequestBody Manager manager) {
        boolean flag = managerService.insertManager(manager);
        int code = flag ? Code.SAVE_OK : Code.SAVE_ERR;
        String msg = flag ? "数据添加成功" : "数据添加失败";
        return new Result(code, flag, msg);
    }



    @GetMapping("/managercount")
    public Result selectmanager(@RequestParam String managerAcc) {
        if (StringUtils.isEmpty(managerAcc)) {
            throw new IllegalArgumentException("用户账号不能为空");
        }
        Integer count = managerService.selectmanager(managerAcc);
        return new Result(Code.GET_OK, count, "查询成功");
    }
}
